package com.eelpo.framework.socket.handler;

import java.util.concurrent.TimeUnit;

import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.util.Timer;

import com.eelpo.framework.socket.listener.SocketIdleListener;
import com.eelpo.framework.socket.session.SocketSessionCache;

/**
 * Socket idle 处理器
 * 
 * @author <a href="mailto:whz-work@163.com">汪洪州</a>
 * 
 * @since 1.0 Create on May 30, 2012
 */
@Sharable
public class SocketIdleStateHandler extends IdleStateHandler {

	private SocketIdleListener socketIdleListener;

	public SocketIdleStateHandler(Timer timer, int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
		super(timer, readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds);
	}

	public SocketIdleStateHandler(Timer timer, long readerIdleTime, long writerIdleTime, long allIdleTime, TimeUnit unit) {
		super(timer, readerIdleTime, writerIdleTime, allIdleTime, unit);
	}

	public SocketIdleStateHandler(SocketIdleListener socketIdleListener, Timer timer, int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
		super(timer, readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds);
		this.socketIdleListener = socketIdleListener;
	}

	public SocketIdleStateHandler(SocketIdleListener socketIdleListener, Timer timer, long readerIdleTime, long writerIdleTime, long allIdleTime, TimeUnit unit) {
		super(timer, readerIdleTime, writerIdleTime, allIdleTime, unit);
		this.socketIdleListener = socketIdleListener;
	}

	@Override
	protected void channelIdle(ChannelHandlerContext ctx, IdleState state, long lastActivityTimeMillis) throws Exception {
		if (state == IdleState.READER_IDLE) {
			ctx.getChannel().close();
			if (socketIdleListener != null) {
				socketIdleListener.readerIdle(SocketSessionCache.getSocketSession(ctx.getChannel()), lastActivityTimeMillis);
			}
		} else if (state == IdleState.WRITER_IDLE) {
			ctx.getChannel().close();
			if (socketIdleListener != null) {
				socketIdleListener.writerIdle(SocketSessionCache.getSocketSession(ctx.getChannel()), lastActivityTimeMillis);
			}
		} else if (state == IdleState.ALL_IDLE) {
			ctx.getChannel().close();
			if (socketIdleListener != null) {
				socketIdleListener.allIdle(SocketSessionCache.getSocketSession(ctx.getChannel()), lastActivityTimeMillis);
			}
		}
	}
}
